<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">见实力工业企业服务平台</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon
            slot="prefix"
            icon-class="user"
            class="el-input__icon input-icon"
          />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon
            slot="prefix"
            icon-class="password"
            class="el-input__icon input-icon"
          />
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-col :span="6">
          <el-checkbox
            v-model="loginForm.rememberMe"
            style="margin: 0px 0px 2px 0px"
          >记住密码</el-checkbox
          >
        </el-col>
        <el-col :span="18">
          <el-radio-group v-model="loginType">
            <el-radio-button label="1">企业</el-radio-button>
            <el-radio-button label="2">机构</el-radio-button>
            <el-radio-button label="4">园区</el-radio-button>
            <!-- <el-radio-button label="3">运维</el-radio-button> -->
          </el-radio-group>
        </el-col>
      </el-form-item>

      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right" v-if="register">
          <router-link class="link-type" :to="'/register'"
          >立即注册</router-link
          >
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span></span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import axios from "axios";
import { removeToken } from '@/utils/auth'
export default {
  name: "Login",
  data() {
    return {
      client: false,
      server: false,
      operation: false,
      codeUrl: "",
      loginType: [],
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        loginType: null,
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      captchaEnabled: true,
      register: false,
      utcTime: "2025-07-31 12:30:59",
      endTime: "2025-07-31 12:30:59",
      endDate: "2025-07-31 12:30:59",
      redirect: undefined,
      defaultTime: "2125-04-15 00:00:00",
      timeServers: [
        "https://cn.apihz.cn/api/time/getapi.php?id=88888888&key=88888888&type=1"
      ],
      currentTimeServer: 0,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
    //this.getTaobaoTime();
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password:
          password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      };
    },
    // getTaobaoTime() {
    //   this.currentTimeServer = 0;
    //   return new Promise(resolve => {
    //     this.tryNextTimeServer(resolve);
    //   });
    // },
    // tryNextTimeServer(resolve) {
    //   if (this.currentTimeServer >= this.timeServers.length) {
    //     this.utcTime = new Date(this.defaultTime);
    //     resolve(this.utcTime);
    //     return;
    //   }
    //
    //   const currentServer = this.timeServers[this.currentTimeServer];
    //   this.fetchTimeFromServer(currentServer)
    //     .then(time => {
    //       if (!time) {
    //         throw new Error("Invalid time response");
    //       }
    //       this.utcTime = time;
    //       resolve(this.utcTime);
    //     })
    //     .catch(() => {
    //       this.currentTimeServer++;
    //       this.tryNextTimeServer(resolve);
    //     });
    // },
    // fetchTimeFromServer(server) {
    //   return new Promise((resolve, reject) => {
    //     axios
    //       .get(server, {
    //         params: {
    //           _t: new Date().getTime(),
    //         },
    //       })
    //       .then(response => {
    //         let time;
    //         if (server.includes("apihz")) {
    //           time = new Date(response.msg);
    //         } else if (server.includes("taobao")) {
    //           time = new Date(response.data.data.t);
    //         }
    //         resolve(time);
    //       })
    //       .catch(error => {
    //         reject(error);
    //       });
    //   });
    // },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // this.getTaobaoTime().then(utcTime => {
          //   this.utcTime = utcTime;
          //   const endDateTime = new Date(this.endTime);
          //   if (this.utcTime > endDateTime) {
          //     this.$modal.msgError("登录已过期，请重新登录!");
          //     return;
          //   }
          //
          //
          // });
          if (
            this.loginForm.username != "admin" &&
            this.loginForm.username != "见实力工业企业云平台"
          ) {
            if (
              this.loginType.toString() == "" ||
              this.loginType.toString() == undefined ||
              this.loginType.toString() == null
            ) {
              this.$modal.msgError("请选择一个端口进行登录!");
              return;
            }
          }
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), {
              expires: 30,
            });
            Cookies.set("rememberMe", this.loginForm.rememberMe, {
              expires: 30,
            });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.loginForm.loginType = this.loginType.toString();
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" });
              // // 登录后去拉取网络时间
              // axios.get('https://cn.apihz.cn/api/time/getapi.php?id=88888888&key=88888888&type=1')
              //   .then(response => {
              //     console.log(response)
              //     const serverDateTime = new Date(response.data.dateTime); // 用服务器时间
              //     const warningDateTime = new Date(this.endDate); // 你的endDate本身
              //
              //     if (serverDateTime > warningDateTime) {
              //       setTimeout(() => {
              //         console.log("是否执行");
              //         Cookies.remove("username");
              //         Cookies.remove("password");
              //         Cookies.remove("rememberMe");
              //         sessionStorage.clear();
              //         localStorage.clear();
              //         removeToken();
              //         // 如果还需要登出操作，取消注释
              //         // this.$store.dispatch("LogOut").then(() => {});
              //       }, 100); // 给一个小延时确保路由跳转完成
              //     }
              //   })
              //   .catch(error => {
              //     console.error("获取服务器时间失败：", error);
              //     // 这里可以选择是否回退到本地时间判断
              //   });
              this.loading = false; // 登录成功后关闭loading
            })
            .catch(() => {
              this.loading = false; // 登录失败后关闭loading
              if (this.captchaEnabled) {
                this.getCode(); // 刷新验证码
              }
            });
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
// .el-radio-button__inner {
//   margin-left:10px !important
// }
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 550px;
  height: 320px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}
</style>
